package com.lcredu.web.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 黎长容
 * @date 2025-07-25 11:10
 */
@Component
public class MyInterceptor implements HandlerInterceptor {
    /**
     * 黎长容知识
     * 拦截器
     * 1. preHandle : 拦截的handler方法执行前调用
     * 2. postHandle : 拦截的handler方法执行后调用
     * 3. afterCompletion : 视图渲染后执行
     * 4. 在spring配置文件中进行配置
     * 5. 
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("---MyInterceptor---preHandle()---");
        String username = request.getParameter("username");
        if ("lcr".equals(username)) {
            //用户名正确
            return true;
        } else {
            //转发到其他页面
            request.getRequestDispatcher("/error.jsp").forward(request, response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("---MyInterceptor---postHandle()---");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("---MyInterceptor---afterCompletion()---");
    }
}
